package model.dao;

import java.util.List;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import model.entity.Photo;
import model.entity.User;

@Stateless
@Local(PhotoDaoLocal.class)
public class PhotoDaoBean extends GenericDaoBean<Photo, Integer> implements
		PhotoDaoLocal {

	@Override
	public List<Photo> searchTitleOrDescription(String title) {
		try{
			Query q = em
					.createNamedQuery("searchTitleOrDescription");
			q.setParameter("searchString", "%"+title+"%");
			return (List<Photo>) q.getResultList();
		}catch(NoResultException e){
			return null;
		}
	}
	
	@Override
	public List<Photo> searchDimensions(int dimension, boolean greater) {
		try{
			String sign="<";
			if(greater){
				sign=">";
			}
			Query q = em.createQuery("SELECT p FROM Photo p WHERE p.width"+sign+":dim AND p.height"
					+sign+":dim");
			q.setParameter("dim", dimension);
			return (List<Photo>) q.getResultList();
		}catch(NoResultException e){
			return null;
		}
	}
	
	
	@Override
	public List<Photo> searchRate(double rate, boolean greater) {
		try{
			String sign="<";
			if(greater){
				sign=">";
			}
			Query q = em.createQuery("SELECT p FROM Photo p WHERE p.rating"+sign+":rat");
			q.setParameter("rat", rate);
			return (List<Photo>) q.getResultList();
		}catch(NoResultException e){
			return null;
		}
	}

	@Override
	public int removePhotoAlbums(Integer photoId) {
		try{
			Query q = em.createNativeQuery("DELETE FROM albums_for_photo WHERE photo_id=?");
			q.setParameter(1, photoId);
			return  q.executeUpdate();
		}catch(NoResultException e){
			return -1;
		}
	}
	
	@Override
	public int removePhotoFavorites(Integer photoId,Integer albumId) {
		try{
			Query q = em.createNativeQuery("DELETE FROM albums_for_photo WHERE photo_id=? AND album_id=?");
			q.setParameter(1, photoId);
			q.setParameter(2, albumId);
			return  q.executeUpdate();
		}catch(NoResultException e){
			return -1;
		}
	}

	@Override
	public List<Photo> firstNGlobal(Integer amount) {
		try{
			Query q = em.createQuery("Select p FROM Photo p " +
					"WHERE p.pub=TRUE ORDER BY p.uploadDate DESC").setFirstResult(0).setMaxResults(amount);
			return  q.getResultList();
		}catch(NoResultException e){
			return null;
		}
	}



}